#include "SeqList.h"

void SLInit(SL* ps){
    assert(ps);

    ps->a = (SLDataType*)malloc(sizeof(SLDataType)*INIT_CAPACITY);
    if (NULL == ps->a){
        perror("SLInit::malloc");
        return;
    }
    ps->size = 0;
    ps->capacity = INIT_CAPACITY;
}

void SLDestroy(SL* ps){
    assert(ps);

    free(ps->a);
    ps->a = NULL;
    ps->size = 0;
    ps->capacity = 0;
    ps = NULL;
}

void SLPrint(const SL* ps){
    assert(ps);

    for (int i = 0; i < ps->size; ++i){
        printf("%d ", ps->a[i]);
    }
    printf("\n");
}

void SLCheckCapacity(SL* ps){
    assert(ps);
    
    if (ps->size == ps->capacity){                 //自定义类型占用字节   扩容数(每次扩容两倍)
        SLDataType* tmp = (SLDataType*)realloc(ps->a, sizeof(SLDataType) * ps->capacity * 2);
        if(NULL == tmp){
            perror("SLCheckCapacity::realloc");
            return;
        }
        ps->a = tmp;
        ps->capacity *= 2;
    }
}

void SLPushBack(SL* ps, SLDataType x){
    assert(ps);
    
    SLCheckCapacity(ps);
    ps->a[ps->size] = x;
    ++ps->size;
    //ps->a[ps->size++] = x;
}

void SLPopBack(SL* ps){
    assert(ps);
    // 暴力检查
    assert(ps->size > 0 && ps->size <= ps->capacity);
    // 温柔检查
    //if (ps->size <= 0){
    //    printf("已为空");
    //    return;
    //}
    --ps->size;
}

void SLPushFront(SL* ps, SLDataType x){
    assert(ps);

    SLCheckCapacity(ps);
    //int end = ps->size - 1;
    //for (int i = 0; i < ps->size; ++i){
    //    ps->a[end + 1] = ps->a[end];
    //    --end;
    //} //不简洁
    int end = ps->size - 1;
    while (end >= 0){
        ps->a[end + 1] = ps->a[end];
        --end;
    }
    ps->a[0] = x;
    ++ps->size;
}

void SLPopFront(SL* ps){
    assert(ps);
    assert(ps->size > 0);

    int begin = 1;
    while (begin < ps->size){
        ps->a[begin - 1] = ps->a[begin];
        ++begin;
    }
    --ps->size;
}

//pos->数组下标
void SLInsert(SL* ps, int pos, SLDataType x){
    assert(ps);
    //判断插入位置是否非法
    assert(pos >= 0 && pos <= ps->size);

    SLCheckCapacity(ps);
    int end = ps->size - 1;
    while (end >= pos){
        ps->a[end + 1] = ps->a[end];
        --end;
    }
    ps->a[pos] = x;
    ++ps->size;
}

void SLErase(SL* ps, int pos){
    assert(ps);
    //判断删除位置是否非法
    assert(pos >= 0 && pos < ps->size);

    int begin = pos + 1;
    while (begin < ps->size){
        ps->a[begin - 1] = ps->a[begin];
        ++begin;
    }
    --ps->size;
}

int SLFind(SL* ps, SLDataType x){
    assert(ps);

    for (int i = 0; i < ps->size; ++i){
        if (ps->a[i] == x){
            return i;
        }
    }
    return -1;
}